package com.hunttown.mes.manage.controller.interceptor;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Enumeration;

/**
 * 安全拦截器
 * created by wangjunfu on 2017-07-27
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    //JS 统一版本号
    @Value("${js.version}")
    private String jsversion;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //region URL拦截

        //请求地址
        StringBuffer requestUrl = request.getRequestURL();
        requestUrl.append("?imax=");

        //region 解析请求地址的HOST
        String http = requestUrl.substring(0, requestUrl.indexOf("//") + 2);
        String domain = requestUrl.substring(requestUrl.indexOf("//") + 2);
        domain = domain.substring(0, domain.indexOf("/"));
        String Host = http + domain;                 //不带最后的斜杠“/”
        String scheme = request.getScheme();         //协议头，http还是https？需要在tomcat中配置
        String HostDomain = scheme + "://" + domain; //不带最后的斜杠“/”
        //endregion

        //当前页面地址
        StringBuffer handleUrl = request.getRequestURL();
        handleUrl.append("?imax=");

        //请求地址，不带主机头
        StringBuilder historyPath = new StringBuilder(request.getRequestURI());
        historyPath.append("?imax=");

        //审批URL
        request.setAttribute("applyUrl", request.getRequestURL());

        //是否是分页URL
        boolean isPageUrl = false;

        //操作完成当前页面后的重定向地址
        String redirectUrl = "";

        StringBuilder parmUrl = new StringBuilder();

        //获取请求参数
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            if (paraName.equals("pn") || paraName.equals("pageSize")) {
                isPageUrl = true;
                historyPath.append("&").append(paraName).append("=").append(request.getParameter(paraName));
            }
            if (!paraName.equals("pn") && !paraName.toLowerCase().equals("redirecturl")) {
                parmUrl.append("&").append(paraName).append("=").append(request.getParameter(paraName));
            }
            if (paraName.toLowerCase().equals("redirecturl")) {
                redirectUrl = request.getParameter(paraName);
            }
        }

        //是否是分页URL
        if (isPageUrl) {
            requestUrl.append(parmUrl);

            //将当前访问路径保存到历史路径中，和index页的cookie一致
            historyPath.append(parmUrl);
            CookieUtils.setCookie(response, "historyPath", historyPath.toString(), 8 * 3600);
        }

        //完整带参数URL
        handleUrl.append(parmUrl);

        if (modelAndView != null) {
            modelAndView.addObject("requestUrl", requestUrl);
            modelAndView.addObject("handleUrl", handleUrl);
            modelAndView.addObject("redirectUrl", URLDecoder.decode(redirectUrl, "utf-8"));

            String viewName = modelAndView.getViewName();
            if (viewName.startsWith("/")) { //有时会写成"/home/index"
                viewName = viewName.substring(1);
            }
            viewName = viewName.replace("/", "-");
            modelAndView.addObject("ViewName", viewName);

            //JS 统一版本号
            modelAndView.addObject("JsVersion", jsversion);

            //当前用户PIN
            String pin = CookieUtils.getCookieByName(request, KeyConstants.ADMIN_COOKIE);
            modelAndView.addObject("PIN", pin);

            //HOST
            modelAndView.addObject("Host", Host);
            modelAndView.addObject("Domain", domain);
            modelAndView.addObject("HostDomain", HostDomain);
        }
        //endregion

    }
}